package me.aartikov.flowscreenswitchersample.ui;

import me.aartikov.alligator.NavigationContext;
import me.aartikov.alligator.NavigationContextBinder;
import me.aartikov.alligator.Navigator;
import me.aartikov.alligator.Screen;
import me.aartikov.alligator.helpers.BaseAbility;
import me.aartikov.alligator.helpers.FractionStack;
import me.aartikov.alligator.screenswitchers.FragmentScreenSwitcher;
import me.aartikov.flowscreenswitchersample.ResourceTable;
import me.aartikov.flowscreenswitchersample.SampleApplication;
import me.aartikov.flowscreenswitchersample.screens.TestFlowScreen;
import ohos.aafwk.content.Intent;
import ohos.agp.window.service.WindowManager;

import java.util.List;

public class MainAbility extends BaseAbility {

    private Navigator mNavigator;
    private NavigationContextBinder mNavigationContextBinder;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mNavigator = SampleApplication.getNavigator();
        mNavigationContextBinder = SampleApplication.getNavigationContextBinder();
    }

    @Override
    protected void onActive() {
        super.onActive();
        bindNavigationContext();
        setInitialFragmentIfRequired();
    }


    private void setInitialFragmentIfRequired() {
        List<Screen> screens = FractionStack.getInstance(getFractionManager()).getCurrentFragmentScreen(this.toString());
        if (screens.size() == 0 && mNavigator.canExecuteCommandImmediately()) {
            mNavigator.goForward(new TestFlowScreen(ResourceTable.Id_flow_fragment_container, this.toString()));
        } else {
            mNavigator.reduce(screens);
        }
    }

    private void bindNavigationContext() {
        NavigationContext.Builder builder = new NavigationContext.Builder(this, SampleApplication.getNavigationFactory())
                .flowFragmentNavigation(getFractionManager())
                .fragmentNavigation(getFractionManager())
                .screenSwitcher(new FragmentScreenSwitcher(SampleApplication.getNavigationFactory(), getFractionManager()))
                .screenSwitchingListener((screenFrom, screenTo) -> bindNavigationContext());
        mNavigationContextBinder.bind(builder.build());
    }

    @Override
    protected void onBackPressed() {
        if (!mNavigator.goBack()) {
            super.onBackPressed();
        }
    }
}
